<template>
  <div v-loading="submitLoading" class="affix-container"
    style="display: flex;flex-direction: column;height: 100%;flex: 1;" element-loading-text="加载中...">
    <!-- 创建工单 -->
    <div class="top_app">
      <div class="app-container-inner">
        <div class="create-order">
          <div class="flex-align-center">
            <h4 class="title">创建工单</h4>
            <div class="tip_sty">您当前可下单金额为：<span> {{ (detailData?.money
    - detailData?.freezeMoney).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }}</span>元 , 暂冻结金额为：<span>{{
    detailData?.freezeMoney.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }}</span>元，余额为：<span>{{
    detailData?.money.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }}</span>元</div>
          </div>
          <div class="btns">
            <button class="btn btn-bg2 " @click="submitOrder(ruleFormRef)">提交工单</button>
            <button class="btn btn-bg5" @click="onCancelOrder">取消</button>
          </div>
        </div>
      </div>
    </div>
    <div class="sty_bigbox">
      <div class="big_box">
        <!-- 工单基本信息 -->
        <div class="serve-message">
          <div class="app-container">
            <div class="app-container-inner ">
              <el-form label-position="right" ref="ruleFormRef" :rules="rules" label-width="90px" :model="basicData"
                class="oard_form">
                <div class="order_basic">
                  <div style="flex: 1;">
                    <h4 class="title">工单信息</h4>
                    <div style="margin-top: 10px;">
                      <el-form-item label="工单模块" prop="moduleId">
                        <el-select placeholder="请选择" filterable clearable v-model="basicData.moduleId"
                          :remote-method="getworkModulePageSelectChange" :loading="loading" remote remote-show-suffix>
                          <el-option v-for="item in modules" @click="changemodules(item)" :value="item.id"
                            :disabled="item.select" :label="`${item.name}`" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="服务级别">
                        <el-select class="w200" filterable clearable v-model="basicData.grade"
                          :remote-method="getworkLevelPageSelectChange" :loading="loading" remote remote-show-suffix>
                          <el-option v-for="item in grades" :value="item.id" :label="item.name" :key="item.id" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="工单内容">
                        <el-input class="form-control" :rows="2" v-model="basicData.content" type="textarea"
                        maxlength="500" placeholder="请输入工单内容" show-word-limit />
                      </el-form-item>
                      <el-form-item label="商家备注">
                        <el-input class="form-control" :rows="2" v-model="basicData.remark" type="textarea"
                        maxlength="500" placeholder="展示给平台看的备注" show-word-limit />
                      </el-form-item>
                      <el-form-item label="工单图片">
                        <div class="upload_img">
                          <el-upload :auto-upload="false" list-type="picture-card" :on-preview="lookFile"
                            :on-remove="deleteItem" accept="image/*" drag action="#" multiple :on-change="handleChange"
                            v-model:file-list="fileList" :limit="10" :on-exceed="onExceed">
                            <el-icon size="16">
                              <Plus />
                            </el-icon>
                          </el-upload>
                        </div>
                      </el-form-item>
                    </div>
                  </div>
                  <div style="flex: 1;" class="basic-order" ref="right_addition">
                    <h4 class="title">客户信息</h4>
                    <div style="margin-top: 10px;">
                      <!--地址识别-->
                      <el-form-item label="地址识别">
                        <div class="address_identify_content">
                          <el-input v-model="textAddress" class="textarea" maxlength="300" show-word-limit
                            placeholder="粘贴地址识别,示例：张三 139****9999 广东省中山市石歧区某小区" rows="3" type="textarea" />
                          <el-button :loading="textLoading" class="btn" @click="onAddressParser"
                            :disabled="!textAddress.trim()">识别
                          </el-button>
                        </div>
                      </el-form-item>
                      <el-form-item label="客户名称" prop="name">
                        <el-popover ref="popoverInputRef" popper-class="monitor-yt-popover" :width="300"
                          :visible="visibleSearch" placement="bottom">
                          <div style="max-height: 300px;overflow: auto;">
                            <div class="user_item" @click="changeuserPeerson(item)" v-for="item in userPersons"
                              :value="item.id" :label="item.phone" :item="item">
                              {{ item.name + ' ' + item.phone }}</div>
                          </div>
                          <template #reference>
                            <el-input placeholder="请输入客户名称" clearable v-model="basicData.name" @input="inputSearchName"
                              @blur="visibleSearch = false" @focus="getselecUser('')" @clear="onClearUser" />
                          </template>
                        </el-popover>
                      </el-form-item>
                      <el-form-item label="客户电话" prop="phone">
                        <el-input placeholder="请输入联系电话" maxlength="11"
                          @input="basicData.phone = basicData.phone.replace(/[^0-9]/g, '')" v-model="basicData.phone" />
                      </el-form-item>
                      <el-form-item label="客户地址" required prop="area"
                        :rules="[{ required: true, message: '请选择地址', trigger: ['blur', 'change'] }]">
                        <SingleAddress ref="addrsDom" @value-change="addressValChange" :address="addrs" />
                      </el-form-item>
                      <el-form-item label="详细地址" prop="address">
                        <el-input placeholder="请输入详细地址" v-model="basicData.address" show-word-limit maxlength="200"
                          type="textarea" :rows="2" />
                      </el-form-item>

                    </div>
                  </div>
                </div>
              </el-form>
            </div>
          </div>
          <el-aside width="380px" v-if="submitFormShow" key="customfieldList">
            <div class="right_aside">
              <h4 class="title">自定义字段</h4>
              <div class="oard_form_" :style="{ height: setH + 'px' }">
                <el-form label-position="right" label-width="auto" ref="formRef" :model="basicData">
                  <div v-for="(item, bigindex) in basicData.customfieldList" :key="bigindex">
                    <el-form-item :label="item.name" :required="item.required"
                      :prop="`customfieldList[${bigindex}][${item.type === 5 || item.type === 6 || item.type === 7 ? 'imgArr' : 'val'}]`"
                      :rules="[{ required: item.required, message: item.tip || '必填', trigger: ['blur', 'change'] }]">
                      <!-- 文本 -->
                      <el-input v-if="item.type === 1" :placeholder="item.tip" type="text" v-model="item.val"
                        clearable></el-input>
                      <!-- 多行文本 -->
                      <el-input v-if="item.type === 2" class="form-control" :rows="1" v-model="item.val" type="textarea"
                        maxlength="50" :placeholder="item.tip" show-word-limit />
                      <!-- 单选 -->
                      <el-select v-model="item.val" v-if="item.type === 3 && item.contents.length > 3"
                        :placeholder="item.tip" clearable>
                        <el-option v-for="i in item.contents" :key="i.id" :label="i.val" :value="i.val" />
                      </el-select>
                      <el-radio-group v-else-if="item.type === 3" v-model="item.val">
                        <el-radio v-for="i in item.contents" :label="i.val">{{ i.val }}</el-radio>
                      </el-radio-group>
                      <!-- 多选 -->
                      <el-select v-model="item.val" v-if="item.type === 4 && item.contents.length > 3"
                        :placeholder="item.tip" clearable multiple collapse-tags collapse-tags-tooltip>
                        <el-option v-for="i in item.contents" :key="i.id" :label="i.val" :value="i.val" />
                      </el-select>
                      <el-checkbox-group v-else-if="item.type === 4" v-model="item.val">
                        <el-checkbox v-for="i in item.contents" :key="i.id" :label="i.val">{{ i.val }}</el-checkbox>
                      </el-checkbox-group>
                      <!-- 图片 -->
                      <div class="upload_file" v-if="item.type === 5 || item.type === 6 || item.type === 7"
                        :key="bigindex">
                        <el-upload :auto-upload="false" v-model="item.imgArr"
                          :accept="item.type == 5 ? 'image/*' : item.type == 6 ? '.pdf' : 'video/*'" drag action="#"
                          multiple :show-file-list="false" :on-change="(file) => { handleChange2(file, item) }">
                          <el-icon class="up_icon"><upload-filled /></el-icon>
                          <div>点击上传图片或者文件</div>
                        </el-upload>
                        <ul class="ul_list">
                          <li class="li_item" v-for="(it, index) in item.imgArr">
                            <div class="li_item_left">
                              <img :src="pdf" alt="" style="width: 30px; height: 30px;cursor: pointer"
                                @click.stop="lookFile(it.img)" v-if="(it.name.replace(/.+\./, '') == 'pdf')">
                              <el-icon style="cursor: pointer;" v-else-if="it.file.type.includes('video/')" size="30"
                                @click.stop="lookFile(it.img)">
                                <Film />
                              </el-icon>
                              <el-image v-else :preview-src-list="[it.img]"
                                style="width: 30px; height: 30px;z-index: 99;" :src="it.img" fit="cover" />
                              <span class="pic_name">{{ it.name }}</span>
                            </div>
                            <el-icon size="16" style="cursor: pointer;" @click.stop="deleteItem2(bigindex, index)">
                              <Delete />
                            </el-icon>
                          </li>
                        </ul>
                      </div>
                      <!-- 评分 -->
                      <el-rate v-if="item.type === 8" allow-half v-model="item.val" /><span v-if="item.type === 8">{{
    item.val * 2 }}</span>
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </div>
          </el-aside>
        </div>

        <!-- 商品信息 -->
        <div class="app-container" style="padding-bottom: 12px;">
          <div class="app-container-inner">
            <div class="code-message">
              <h4 class="title">商品信息</h4>
              <!-- <button class="btn btn-bg2 addbtn" @click="goProductDialog">+添加商品</button> -->
              <div class="table-code">
                <el-table :border="true" stripe resizable :data="tableData" style="width: 99.8%" height="260px">

                  <template #empty>
                    <el-empty description="" :image-size="100">
                      <template #description>
                        <span class="el_empty" @click="goProductDialog">添加商品</span>
                      </template></el-empty>
                  </template>
                  <el-table-column label="序号" width="70" fixed>

                    <template v-slot="scope">
                      <span class="order"> {{ scope.$index + 1 }} </span>
                      <span class="add_delete">
                        <el-icon size="16" color="#007cff" class="add" @click="goProductDialog">
                          <CirclePlus />
                        </el-icon>
                        <el-icon color="rgba(245, 108, 108, 1)" size="16" @click="detelePro(scope.$index, scope.row)">
                          <Delete />
                        </el-icon>
                      </span>
                    </template>
                  </el-table-column>
                  <el-table-column label="一物一码" prop="code" show-overflow-tooltip width="150">

                    <template v-slot="i">
                      <el-input placeholder="默认临时编码" v-model="i.row.code" maxlength="30"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="品牌" min-width="140" prop="goodsBrand" show-overflow-tooltip>
                    <template v-slot="i">
                      <el-select placeholder="请选择" filterable clearable v-model="i.row.goodsBrand"
                        @change="getOrderGoodsSelectList('', i.$index, i.row.goodsBrand)"
                        :remote-method="(val) => goodsBrandListChange(val, i.$index)" :loading="loading" remote
                        remote-show-suffix>
                        <el-option v-for="item in i.row.goodsBrandList" :value="item.id" :disabled="item.select"
                          :label="`${item.name}`" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column label="分类" min-width="140" prop="goodsType" show-overflow-tooltip>
                    <template v-slot="i">
                      <el-select placeholder="请选择" :disabled="!i.row.goodsBrand" filterable clearable
                        v-model="i.row.goodsType"
                        @change="getOrderGoodsSelectList('', i.$index, i.row.goodsBrand)"
                        :remote-method="(val) => goodsTypeListChange(val, i.$index, i.row.goodsBrand)"
                        :loading="loading" remote remote-show-suffix>
                        <el-option v-for="item in i.row.goodsTypeList" :value="item.id" :disabled="item.select"
                          :label="`${item.name}`" />
                      </el-select>
                    </template>
                  </el-table-column> -->
                  <el-table-column label="商品名称" min-width="140" prop="goodsId" show-overflow-tooltip>
                    <template v-slot="i">
                      <el-select placeholder="请选择" :disabled="!i.row.goodsBrand" filterable clearable
                        v-model="i.row.goodsId" @change="getOrderGoodsSpecSelectList(i.$index, i.row.goodsId)"
                        :remote-method="(val) => goodsModeListChange(val, i.$index, i.row.goodsBrand)"
                        :loading="loading" remote remote-show-suffix>
                        <el-option v-for="item in i.row.goodsModeList" :value="item.id" :disabled="item.select"
                          :label="`${item.name}`" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="规格" min-width="140" prop="goodsSpecId" show-overflow-tooltip>
                    <template v-slot="i">
                      <el-select placeholder="请选择" :disabled="!i.row.goodsId" filterable clearable
                        v-model="i.row.goodsSpecId">
                        <el-option v-for="item in i.row.goodsSpecNameList" :value="item.id" :disabled="item.select"
                          :label="`${item.name}`" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" prop="qty" min-width="60">

                    <template v-slot="item">
                      <el-input v-model="item.row.qty"
                        @input="item.row.qty = item.row.qty.toString().replace(/[^0-9]/g, '')" />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
        <!-- 附加信息 -->
        <div class="app-container" style="padding-bottom: 12px;padding-top: 0;">
          <div class="app-container-inner">
            <div class="code-message">
              <h4 class="title">附加信息</h4>
              <el-form label-position="right" label-width="90px">
                <div class="flex-align-center" style="margin-top: 12px;">
                  <el-form-item label="工单来源">
                    <el-input placeholder="商家名称" disabled :value="detailData?.factoryName" />
                  </el-form-item>
                  <el-form-item label="本单冻结金额" label-width="190px">
                    <el-input disabled :value="settlementPrice">
                      <template #prepend>￥</template>
                    </el-input>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件查看 -->
    <el-dialog title="查看" v-model="dialogContract" :draggable="true">
      <iframe :src="`${file}`" frameborder="0" height="100%" style="height: 700px" width="100%"></iframe>
    </el-dialog>

    <!-- 创建客户 -->
    <el-dialog title="创建客户" width="400px" v-model="createUserDialogVisit" :draggable="true">
      <el-form ref="createUserRef" :model="createUserForm" :rules="createUserFormRules" label-width="90px"
        label-position="left">
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="createUserForm.name" placeholder="请输入客户姓名" clearable />
        </el-form-item>
        <el-form-item label="客户手机号" prop="phone">
          <el-input v-model="createUserForm.phone" placeholder="请输入客户手机号"
            @input="createUserForm.phone = createUserForm.phone.replace(/[^0-9]/g, '')" maxlength="11" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createUserDialogVisit = false">取消</el-button>
          <el-button class="btn-bg2" @click="onSaveCreateUser(createUserRef)">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import pdf from '@/assets/image/pdf.png'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import type { UploadFile, UploadProps, FormInstance, FormRules } from 'element-plus'
import { workLevelPageSelect, workModulePageSelect, getModuleField, getCreateOrderBalance, getOrderBrandSelect, getOrderGoodsTypeSelect, getOrderGoodsSelect, getOrderGoodsSpecSelect, addSave, getUserSelect } from './../../../api/order'
import { addressRecognition } from '../../../api/map'
import SingleAddress from '../../../components/address/singleAddress.vue'
import { orderAnnexUpload, orderVideoUpload } from './../../../api/upload'
import { useSettingStore } from "../../../store/modules/setting"
import { useTagsViewStore } from '../../../store/modules/tagsView'
import * as  _ from 'lodash'

const SettingStore = useSettingStore()
// 刷新页面
const refresh = () => {
  SettingStore.setReload()
}
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const addrsDom = ref()//地址dom
const formRef = ref()
const submitLoading = ref(false)//提交工单loading
const grades = ref(null)// 服务级别
const userPersons = ref()
const fileList = ref([])
const modules = ref(null)// 工单模块
const loading = ref(false)

const dialogContract = ref(false)//文件查看弹窗
const file = ref()//文件
const orderGoodsTypes = ref([])//添加商品信息

const addrs = ref({// 地址
  province: "",
  city: "",
  area: "",
  town: "",
})
const submitFormShow = ref(false)//用来判断是否有自定义字段
//监听查看附件弹窗关闭时销毁 iframe内存
watch(dialogContract, (n) => {
  if (!n) {
    file.value = 'about:blank'
  }
})
const tableData = ref([])//商品列表
const basicData = reactive({
  moduleId: null,//工单类型
  grade: null,//服务级别
  content: '',//故障描述
  remark: '',//商家备注
  userId: '', // 客户ID
  name: '',//姓名
  phone: '',// 客户手机号
  address: "",//详细地址
  area: '',
  customfieldList: [{
    contents: [{ id: null, val: null }],
    moduleFieldId: null,
    name: null,
    required: true,
    status: null,
    tip: '',
    type: null,
    uploadQty: null,
    uploadSize: null,
    val: null,
    imgArr: [],
    workFieldId: '',
  }]
})
const createUserDialogVisit = ref(false) // 创建客户弹窗
const createUserRef = ref()
// 创建客户对象
const createUserForm = reactive({
  name: '', // 客户姓名
  phone: '' // 客户手机号
})
const rules = reactive({
  moduleId: [{ required: true, message: '请选择工单模块', trigger: 'change' }],
  phone: [{ required: true, message: '请输入客户手机号', trigger: ['change', 'blur'] }, {
    required: true, validator: (rule: any, value: any, callback: any) => {
      if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(basicData.phone)) {
        return callback(new Error('手机号格式错误'))
      }
      callback()
    }, trigger: ['change', 'blur']
  }],
  name: [{ required: true, message: '请输入客户姓名', trigger: ['change', 'blur'] }],
  address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }]
})

// 校验规则
const createUserFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '客户姓名不能为空', trigger: ['change', 'blur'] },
    { required: true, max: 100, message: '客户姓名长度限制 2~100', trigger: ['change', 'blur'] }
  ],
  phone: [
    { required: true, message: '客户手机号不能为空', trigger: ['change', 'blur'] },
    {
      required: true, validator: (rule: any, value: any, callback: any) => {
        if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(createUserForm.phone)) {
          return callback(new Error('手机号格式错误'))
        }
        callback()
      }, trigger: ['change', 'blur']
    }
  ]
})
const textAddress = ref('')//地址识别信息
const textLoading = ref(false)
const onAddressParser = _.debounce(async () => {
  textLoading.value = true
  let data = {
    text: textAddress.value.trim()
  }
  await addressRecognition(data).then(res => {
    if (res.data.success) {
      let item = res.data.data.row
      nextTick(() => {
        addrs.value = {
          province: item.province,
          city: item.city,
          area: item.area,
          town: item.town
        }
      })
      basicData.userId = ''
      basicData.name = item.username
      basicData.phone = item.phone
      let str = ''
      str = item.text.replace(item.phone, '')
      str = str.replace(item.username, '')
      str = str.replace(item.province, '')
      str = str.replace(item.city, '')
      // 去除字符串中所有的标点符号，只保留中文、英文和数字
      basicData.address = str.replace(/[`:_.~!@#$%^&*() \+ =<>?"{}|, \/ ;' \\ [ \] ·~！@#￥%……&*（）—— \+ ={}|《》？：“”【】、；‘’，。、]/g,
        '').trim()
    } else {
      ElMessage({
        message: res.data.message,
        type: 'error',
      })
    }
  })
  textLoading.value = false
}, 500)
// 点击 添加商品按钮
const goProductDialog = async () => {
  tableData.value.push({ code: '', goodsBrand: '', goodsBrandList: [], goodsId: '', goodsModeList: [], goodsSpecId: '', goodsSpecNameList: [], qty: 1 })
  let index = tableData.value.length - 1
  await getOrderBrandSelectList('', index)
  tableData.value[index].goodsBrand = tableData.value[index].goodsBrandList[0].id
  // await getOrderGoodsTypeSelectList('', index, tableData.value[index].goodsBrand)
  // tableData.value[index].goodsType = tableData.value[index].goodsTypeList[0].id
  await getOrderGoodsSelectList('', index, tableData.value[index].goodsBrand)
  tableData.value[index].goodsId = tableData.value[index].goodsModeList[0].id
  await getOrderGoodsSpecSelectList(index, tableData.value[index].goodsId)
  tableData.value[index].goodsSpecId = tableData.value[index].goodsSpecNameList[0].id
}
// 删除产品
const detelePro = (i, row) => {
  tableData.value = tableData.value.filter((o, index) => {
    return index != i
  })
}
// ***********品牌下拉************
const getOrderBrandSelectList = async (val, index) => {
  let data = {
    "keyword": val,
    "limit": 0,
    "page": 0
  }
  await getOrderBrandSelect(data).then(res => {
    if (res?.data) {
      tableData.value[index].goodsBrandList = res.data.data.rows
    }
  })
}
const brandValue = ref({ val: '', index: null })
const goodsBrandListChange = (val, index) => {
  brandValue.value.val = val
  brandValue.value.index = index
}
watch(() => brandValue.value.val, (n) => {
  getOrderBrandSelectList(brandValue.value.val, brandValue.value.index)
})
// *************end****************
// *********分类下拉***********
// const getOrderGoodsTypeSelectList = async (val, index, brandId) => {
//   tableData.value[index].goodsTypeList = []
//   tableData.value[index].goodsType = null
//   tableData.value[index].goodsModeList = []
//   tableData.value[index].goodsId = null
//   tableData.value[index].goodsSpecNameList = []
//   tableData.value[index].goodsSpecId = null
//   if (!brandId) return
//   let data = {
//     "keyword": val,
//     "limit": 0,
//     "page": 0
//   }
//   await getOrderGoodsTypeSelect(data, brandId).then(res => {
//     if (res?.data) {
//       tableData.value[index].goodsTypeList = res.data.data.rows
//     }
//   })
// }
// const typeValue = ref({ val: '', index: null, brandId: null })
// const goodsTypeListChange = (val, index, brandId) => {
//   typeValue.value.val = val
//   typeValue.value.index = index
//   typeValue.value.brandId = brandId
// }
// watch(() => typeValue.value.val, (n) => {
//   getOrderGoodsTypeSelectList(typeValue.value.val, typeValue.value.index, typeValue.value.brandId)
// })
// ***********end******************
// *********型号下拉***********
const getOrderGoodsSelectList = async (val, index, brandId) => {
  tableData.value[index].goodsModeList = []
  tableData.value[index].goodsId = null
  tableData.value[index].goodsSpecNameList = []
  tableData.value[index].goodsSpecId = null
  if (!brandId) return
  let data = {
    "keyword": val,
    "limit": 0,
    "page": 0
  }
  await getOrderGoodsSelect(data, brandId).then(res => {
    if (res?.data) {
      tableData.value[index].goodsModeList = res.data.data.rows
    }
  })
}
const modeValue = ref({ val: '', index: null, brandId: null, typeId: null })
const goodsModeListChange = (val, index, brandId) => {
  modeValue.value.val = val
  modeValue.value.index = index
  modeValue.value.brandId = brandId
}
watch(() => modeValue.value.val, (n) => {
  getOrderGoodsSelectList(modeValue.value.val, modeValue.value.index, modeValue.value.brandId)
})
// ***********end******************
// *********规格下拉***********
const getOrderGoodsSpecSelectList = async (index, modeId) => {
  tableData.value[index].goodsSpecNameList = []
  tableData.value[index].goodsSpecId = null
  if (!modeId) return
  await getOrderGoodsSpecSelect(modeId).then(res => {
    if (res?.data) {
      tableData.value[index].goodsSpecNameList = res.data.data.rows
    }
  })
}
// ***********end******************
// 用户下拉选项选择改变
const changeuserPeerson = (item) => {
  visibleSearch.value = false
  nextTick(() => {
    addrs.value = {
      province: item.province,
      city: item.city,
      area: item.area,
      town: item.town
    }
  })
  basicData.userId = item.id
  basicData.name = item.name
  basicData.phone = item.phone
  basicData.address = item.address
}
// 所属地址
function addressValChange() {
  addrs.value = addrsDom.value.getSelectAddr()
  basicData.area = addrs.value.area

}
// 取消工单
const onCancelOrder = () => {
  useTagsViewStore().delView(router.currentRoute.value.path)
  router.push({ path: '/order/list' })
}

// 提交工单
const submitOrder = async (formEl: FormInstance | undefined) => {
  basicData.area = addrs.value.area
  if (!formEl) return
  let tt = await submitForm(formRef.value)
  if (!formRef.value) {
    tt = true
  }
  await formEl.validate(async (valid) => {
    if (valid && tt) {
      const useAddr = addrsDom.value.getSelectAddr()
      if (!useAddr.province) {
        ElMessage({
          message: '请选择联系地址',
          type: 'warning'
        })
        return
      }
      orderGoodsTypes.value = []
      if (tableData.value.length == 0) {
        ElMessage({
          message: '至少添加一个商品',
          type: 'warning'
        })
        return
      } else {
        orderGoodsTypes.value = tableData.value.map(o => {
          return {
            goodsId: o.goodsId, code: o.code, goodsSpecId: o.goodsSpecId, qty: o.qty
          }
        })
      }

      let data: any = {
        content: basicData.content,//故障描述
        "goodsVos": orderGoodsTypes.value,//工单商品
        "images": [],//工单图片
        "moduleId": basicData.moduleId,//工单模块ID
        "orderUser": {
          "name": basicData.name,//客户姓名
          "phone": basicData.phone,//客户手机号
          "userId": basicData.userId, //客户ID
          "province": useAddr.province,//地址-省
          "city": useAddr.city,//地址-市
          "area": useAddr.area,//地址-县/区
          "town": useAddr.town,//地址-镇
          "address": basicData.address,//客户详细地址
        },
        remark: '',//商家备注
        "workLevelId": basicData.grade,//工单级别ID
        "workFieldVals": [], //工单自定义字段值对象,
      }
      submitLoading.value = true
      // 判断是否有图片
      if (fileList.value?.length > 0) {
        let imageList = fileList.value.map(o => {
          return o.raw
        })
        // 上传图片
        data.images = []
        await orderAnnexUpload(imageList).then(res => {
          if (res.data.success) {
            data.images = res.data.data.rows
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
            })
            return
          }
        })
      }
      // 判断是否有自定义字段文件上传
      if (submitFormShow.value) {
        for (const key in basicData.customfieldList) {
          let item = basicData.customfieldList[key]
          if (item.type == 5 || item.type == 6 || item.type == 7) {
            let img = []
            for (const i in item.imgArr) {
              const it = item.imgArr[i]
              img.push(it.file)
            }
            if (img.length > 0) {
              if (item.type == 7) {
                await orderVideoUpload(img).then(res => {
                  if (res.data.success) {
                    item.val = []
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.val.push(res.data.data.rows[i])
                    }
                  } else {
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                    })
                  }
                })
              } else {
                await orderAnnexUpload(img).then(res => {
                  if (res.data.success) {
                    item.val = []
                    for (let i = 0; i < res.data.data.rows.length; i++) {
                      item.val.push(res.data.data.rows[i])
                    }
                  } else {
                    ElMessage({
                      message: res.data.message,
                      type: 'error',
                    })
                  }
                })
              }
            }
          }
          if (item.type == 8) {
            if (item.val) {
              item.val = item.val * 2
            }
          }
        }
        data.workFieldVals = _.cloneDeep(basicData.customfieldList)
      }
      data.workFieldVals = data.workFieldVals.map(o => {
        let tmp = []
        if (Array.isArray(o.val)) {
          tmp = o.val.map(i => {
            return { id: null, optValue: i }
          })
        } else {
          tmp = [{ id: null, optValue: o.val }]
        }
        return {
          id: null,
          moduleFieldId: o.moduleFieldId,
          name: o.name,
          optionVos: tmp,
          type: o.type,
          workFieldId: o.workFieldId
        }

        /*
        return { ...o, optionVos: tmp }
        */

      })

      await addSave(data).then(async res => {
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
        if (res.data.success) {
          formEl.resetFields()
          addrsDom.value.clearSelectAddr()
          useTagsViewStore().delVisitedView(router.currentRoute.value.path)
          useTagsViewStore().removeView(router.currentRoute.value.path)
          router.push({ path: '/order/list' })
          refresh()
        }
      })
      submitLoading.value = false
    } else {
      ElMessage({
        message: '请输入完整信息！',
        type: 'error',
      })
    }
  })
}
// 自定义字段
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  let tem = true
  await formRef.value.validate((valid) => {
    if (valid) {
      tem = true
    } else {
      tem = false
    }
  })
  return tem
}
// 获取图片
const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile, uploadFiles) => {
  fileList.value = uploadFiles
}
const onExceed = (val) => {
  ElMessage({
    showClose: true,
    message: `数量不能超过10张!`,
    type: 'error',
    duration: 2000,
  })
}
// 删除图片
const deleteItem = (index) => {
  // console.log(index);
  // console.log(fileList.value);

}
// 查看图片
const lookFile = (val) => {
  file.value = val.url || val
  dialogContract.value = true
}

// 请求获取下拉数据
onMounted(() => {
  Promise.all([getFactoryBalanceData(),
  getworkModulePageSelect(''),
  getworkLevelPageSelect(''),
  goProductDialog()])
  // getFactoryBalanceData()//余额
  // getworkModulePageSelect('')//模块
  // getworkLevelPageSelect('')//级别
  // // getFactoryBalanceRowData()
  // goProductDialog()//添加
  // getselecUser('')
})
// 获取可下单金额详情
const detailData = ref()
const getFactoryBalanceData = async () => {
  // loading.value = true
  await getCreateOrderBalance().then(res => {
    if (res) {

      if (!res.data.success) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
        })
      } else {
        detailData.value = res.data.data.row
      }
    }
  })
  // loading.value = false
}
// 获取图片
const handleChange2 = (uploadFile: UploadFile, item: any) => {
  if (item.uploadSize < uploadFile.size / 1024 / 1024) {
    onExceedSize2(item)
    return
  }
  if (item.imgArr.length >= item.uploadQty) {
    onExceedNub2(item)
    return
  }
  let { uid, name } = uploadFile.raw!
  let tmp = { uid, name, img: window.URL.createObjectURL(uploadFile.raw!), file: uploadFile.raw! }
  item.imgArr.push(tmp)
}
const onExceedNub2 = _.debounce((item) => {
  ElMessage({
    showClose: true,
    message: `${item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频'} 数量不能超过 ${item.uploadQty}!`,
    type: 'error',
    duration: 4000,
    offset: 200
  })
}, 10)
const onExceedSize2 = _.debounce((item) => {
  ElMessage({
    showClose: true,
    message: item.type == 5 ? '图片' : item.type == 6 ? '附件' : '视频' + '大小不能超过' + item.uploadSize + 'MB!',
    type: 'error',
    duration: 4000,
    offset: 200
  })
}, 10)
// 删除图片
const deleteItem2 = (bigindex: number, index: any) => {
  basicData.customfieldList = basicData.customfieldList.map((arr, j) => {
    if ((arr.type == 5 || arr.type == 6 || arr.type == 7) && j == bigindex) {
      arr.imgArr = arr.imgArr.filter((o, i) => i != index)
    }
    return arr
  })
}
const right_addition = ref()

const setH = ref(null)
onMounted(() => {
  // 监听dom的变化
  rightAddition.observe(right_addition.value)
})
// 自定义字段高度
const rightAddition = new ResizeObserver(val => {
  setH.value = val[0].contentRect.height - 30
})
// 销毁
onBeforeUnmount(() => {
  rightAddition.disconnect()
})

// **********工单模块下拉数据*********
const getworkModulePageSelect = (val) => {
  let data = {
    "limit": 0,
    "keyword": val,
    "page": 0
  }
  loading.value = true
  workModulePageSelect(data).then((res) => {
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    loading.value = false
  })
}
const modelValue = ref('')
const getworkModulePageSelectChange = (val) => {
  modelValue.value = val
}
watch(modelValue, (n) => {
  getworkModulePageSelect(n)
})
// *****************end************
// 获取自定义字段
const getModuleFieldlist = async (id) => {
  await getModuleField(id).then(res => {
    res.data.data.rows.length > 0 ? submitFormShow.value = true : submitFormShow.value = false
    basicData.customfieldList = res.data.data.rows.map(o => {
      return { ...o, val: o.type == 4 || o.type == 5 || o.type == 6 || o.type == 7 ? [] : null, imgArr: [] }
    })
  })
}
// // 切换工单
const settlementPrice = ref()
const changemodules = (val) => {
  settlementPrice.value = val.settlementPrice
  getModuleFieldlist(val.id)
  nextTick(() => {
    formRef.value?.resetFields()
  })
}
// 服务级别
const getworkLevelPageSelect = async (val) => {
  let data = {
    "limit": 0,
    "keyword": val,
    "page": 0
  }
  loading.value = true
  await workLevelPageSelect(data).then(async (res) => {
    if (res.data.success) {
      grades.value = await res.data.data.rows
    }
    loading.value = false
  })
}
const leveValue = ref('')
const getworkLevelPageSelectChange = (val) => {
  leveValue.value = val
}
watch(leveValue, (n) => {
  getworkLevelPageSelect(n)
})

// 清除客户账号
const onClearUser = () => {
  basicData.name = ''
  basicData.userId = ''
}
// 保存新客户
const onSaveCreateUser = (formEl: FormInstance) => {
  formEl.validate((valid, fields) => {
    if (!valid) {
      return
    }
    onClearUser()
    basicData.userId = '0'
    basicData.name = createUserForm.name
    basicData.phone = createUserForm.phone
    createUserDialogVisit.value = false
  })
}

// ***************客户列表搜索************
const popoverInputRef = ref()
const visibleSearch = ref(false)
// 输入搜索
const inputSearchName = _.debounce((val) => {
  basicData.userId = null
  if (val.trim()) {
    getselecUser(val)
  }
}, 600)
// 获取用户列表
const getselecUser = (val) => {
  let data = {
    "limit": 0,
    "keyword": val,
    "page": 0
  }
  userPersons.value = []
  getUserSelect(data).then((res) => {
    if (res.data.success) {
      if (res.data.data.rows.length > 0) {
        userPersons.value = res.data.data.rows
        visibleSearch.value = true
      } else {
        visibleSearch.value = false
      }
    }
  })
}

</script>

<style scoped lang="scss">
@import './index';

.userinfo_select_empty {
  display: flex;
  justify-content: center;
}

:deep(.el_empty) {
  color: #007cff;

  &:hover {
    text-decoration: underline
  }

  cursor: pointer;
}

.create-user-btn {
  width: -webkit-fill-available !important;
}
</style>
<style lang="scss">
.el-popover.monitor-yt-popover {
  padding: 6px 0;

  .user_item {
    font-size: 12px;
    padding: 8px 12px;
    cursor: pointer;

    &:hover {
      background-color: rgb(245, 247, 250);
    }
  }
}
</style>
